package com.tencent.sr.iris.activity.service.event.base;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.tencent.sr.iris.activity.common.enums.EventHandingRecordStatusEnum;
import com.tencent.sr.iris.activity.repository.entity.TIrisEventHandingRecordDO;
import com.tencent.sr.iris.activity.service.activity.IrisEventHandingRecordService;
import com.tencent.sr.iris.activity.service.event.vo.IrisEventHandleContext;
import com.tencent.sr.iris.activity.service.event.vo.IrisEventHandleResult;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

/**
 * 事件处理流水模版
 *
 * @author xiaojun
 */
@Slf4j
public abstract class AbstractEventHandingRecordHandler {

    @Resource
    IrisEventHandingRecordService irisEventHandingRecordService;

    /**
     * 活动处理器
     *
     * @param context
     */
    public void execute(IrisEventHandleContext context) {

        List<String> eventHandingInfoList = Lists.newArrayList();
        TIrisEventHandingRecordDO handingRecordDO = irisEventHandingRecordService.queryRecord(context);
        try {
            if (handingRecordDO == null) {
                handingRecordDO = irisEventHandingRecordService.saveHandingRecord(context, eventHandingInfoList);
            }

            //处理事件
            IrisEventHandleResult result = process(context);

            //处理记录
            handingRecordDO.setHandingInfo(JSON.toJSONString(result));
            handingRecordDO.setHandingStatus(EventHandingRecordStatusEnum.SUCCEES.getCode());
        } catch (Exception e) {
            handingRecordDO.setHandingInfo(JSON.toJSONString(handingRecordDO));
            handingRecordDO.setFailCount((byte) (handingRecordDO.getFailCount() + 1));
            handingRecordDO.setHandingStatus(EventHandingRecordStatusEnum.FAIL.getCode());
            log.error(this.getClass().getSimpleName() + " exception context:{}", JSON.toJSONString(context), e);
        } finally {
            irisEventHandingRecordService.updateRecord(handingRecordDO);
        }

    }

    /**
     * 需要实现的具体逻辑
     *
     * @param context
     */
    public abstract IrisEventHandleResult process(IrisEventHandleContext context);


}
